package com.example.secondassignment;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

public class MusicPlayerService extends Service {
	
	private MediaPlayer mediaPlayer = new MediaPlayer();
	private int currentLenghtPlayed;
	private Song currentSongPlaying = null;
	private NotificationManager notifManager;


    @Override
    public void onCreate() {
    	super.onCreate();
        // Tell the user we started.
    	System.out.println("onCreate...MP3Player service");
    
    }
    
    public void playSong(final Song song){
    	if(mediaPlayer.isPlaying() || currentLenghtPlayed == 0){
    		play(song);
    		currentSongPlaying = song;
			dismissNotification();
			setNotification(currentSongPlaying.getName()+" is playing");
    	}
    	else{
    		resumeSong(song);
    		currentSongPlaying = song;
    	}
    }
    
    public void pauseSong(final Song song){
    	mediaPlayer.pause();
    	currentLenghtPlayed = mediaPlayer.getCurrentPosition();
		dismissNotification();
		setNotification(currentSongPlaying.getName()+" is paused"); // Start the notification menu
    }
    public void stopSong(final Song song){
    	mediaPlayer.stop();
    	currentLenghtPlayed = 0;
    }
    public void resumeSong(final Song song){
    	if( !mediaPlayer.isPlaying() ){
    		mediaPlayer.seekTo(currentLenghtPlayed);
    		mediaPlayer.start();
    	}
    	else{
    		showToast(song.getName()+" is already playing");
    	}
    }
    public void nextSong(final Song song){
    	Song nextSong = song.getNext();
    	if(nextSong != null){
    		showToast(nextSong.getName());
    		play(nextSong);
    		currentSongPlaying = nextSong;
			dismissNotification();
			setNotification(currentSongPlaying.getName()+" is playing");
    	}
    }
    public void previousSong(final Song song){
    	if(mediaPlayer.getCurrentPosition() < 5000){ // If its in the begining (>5sec) of the song we will go to the previous one
	    	Song previousSong = song.getPrevious();
	    	if(previousSong != null){
	    		showToast(song.getPrevious().getName());
	    		play(previousSong);
	    		currentSongPlaying = previousSong; 
				dismissNotification();
				setNotification(currentSongPlaying.getName()+" is playing");
	    	}
    	}
    	else {
    		mediaPlayer.seekTo(0); // Start from the begining of the song
    	}
    }
    /**
     * @author Libra
     * 
     * Used to see if the MusicPlayer already has been started or not. 
     * 
     * @return boolean 
     */
    public boolean isPlaying(){
    	if( mediaPlayer.isPlaying() || (currentSongPlaying != null))
    		return true;
    	return false;
    }
    
    public Song getCurrentSong(){
    	return currentSongPlaying;
    	
    }
    
    /* To pull data in case of binding  */
    public int getCount() {
    	return 0;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
    	System.out.println("onStartCommand(...)");
    	return Service.START_STICKY;
    	//return Service.START_NOT_STICKY;  
    }
    
    @Override
    public void onDestroy() {
    	
        System.out.println("onDestroy...MP3Player service");
        super.onDestroy();
    }
    
    public void stopService(){
    	//currentSongPlaying = null;
    	mediaPlayer.stop();
    	dismissNotification();
    	mediaPlayer.release();
    	mediaPlayer = null;
    	MusicPlayerService.this.stopSelf();

    }
    
    /**
	 * use mediaPlayer to play selected song.
	 * Operation sequence with media player is mandatory. 
	 * @param song
	 */
	private void play(final Song song)
	{
		if(song == null) return;

		try
		{
			System.out.println("void play try{");
			if(mediaPlayer.isPlaying()) mediaPlayer.stop(); //Stop current song.

			mediaPlayer.reset(); //reset resource of player
			mediaPlayer.setDataSource(this, Uri.parse(song.getPath())); //set Song to play
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION); //select aoudio stream
			mediaPlayer.prepare(); //prepare resourse
			mediaPlayer.setOnCompletionListener(new OnCompletionListener() //handler onDone
			{
				@Override
				public void onCompletion(MediaPlayer mp)
				{
					play(song.getNext());
				}
			});
			mediaPlayer.start(); //play!
		}
		catch(Exception e)
		{
			showToast("we got an exception");
			Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
	}
   
    /**
     * Binding
     */
    private final IBinder binder = new MusicPlayerBinder();
    
    @Override
    public IBinder onBind(Intent intent) {
    	return binder;
    }

    public class MusicPlayerBinder extends Binder {
    	MusicPlayerService getService() {
    		return MusicPlayerService.this;
    	}
    }
    
    public void setNotification(String msg){
	
		Context ctx = getBaseContext();
		
		/* 1. Setup Notification Builder */			
		NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);  // I use compat builder since my phone uses API 15
		
		/* 2. Configure Notification Alarm */
		builder.setSmallIcon(R.drawable.ic_launcher)
			.setWhen(System.currentTimeMillis())
			.setTicker(msg);
			//.setAutoCancel(true);
			
			
		/* 3. Configure Drop-down Action */
		builder.setContentTitle("Click to return to the MP3Player");
				//.setContentText("Click to continue.")
				//.setContentInfo("Click!");
		Intent newintent = new Intent(ctx, MP3Player.class);   // Notification intent
		PendingIntent notifIntent = PendingIntent.getActivity(ctx, 0, newintent, 0);
		builder.setContentIntent(notifIntent);
		
		/* 4. Create Notification and use Manager to launch it */
		Notification notification = builder.build();
		notification.flags = Notification.FLAG_ONGOING_EVENT; 
	
		String ns = Context.NOTIFICATION_SERVICE;
		notifManager = (NotificationManager) ctx.getSystemService(ns);
		notifManager.notify(MP3Player.NOTIFICATION_ID, notification);
	}
	
	public void dismissNotification(){
		((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(MP3Player.NOTIFICATION_ID);	
	}
    
    /* Diagnostics while developing */
    
    private void showToast(String msg) {
    	Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }
    

}
